import React, { useState, useEffect } from 'react';

function AdvancedCounter() {
  // 使用 useState 钩子管理状态
  const [count, setCount] = useState(0);
  const [step, setStep] = useState(1);
  const [history, setHistory] = useState([]);
  
  // 使用 useEffect 记录历史
  useEffect(() => {
    if (count !== 0) {
      setHistory(prevHistory => [
        ...prevHistory, 
        { value: count, timestamp: new Date().toLocaleTimeString() }
      ].slice(-10)); // 只保留最近的10条记录
    }
  }, [count]);
  
  // 增加计数
  const increment = () => {
    setCount(prevCount => prevCount + Number(step));
  };
  
  // 减少计数
  const decrement = () => {
    setCount(prevCount => prevCount - Number(step));
  };
  
  // 重置计数
  const reset = () => {
    setCount(0);
    setHistory([]);
  };
  
  // 处理步长变化
  const handleStepChange = (e) => {
    const value = Math.max(1, parseInt(e.target.value) || 1);
    setStep(value);
  };
  
  return (
    <div className="advanced-counter">
      <div className="counter-display">{count}</div>
      
      <div className="step-control">
        <label htmlFor="step-input">步长:</label>
        <input
          id="step-input"
          type="number"
          min="1"
          value={step}
          onChange={handleStepChange}
        />
      </div>
      
      <div className="counter-controls">
        <button className="counter-button" onClick={decrement}>减少 {step}</button>
        <button className="counter-button reset" onClick={reset}>重置</button>
        <button className="counter-button" onClick={increment}>增加 {step}</button>
      </div>
      
      <div className="counter-history">
        <h3>历史记录:</h3>
        {history.length === 0 ? (
          <p>暂无记录</p>
        ) : (
          <ul>
            {history.map((record, index) => (
              <li key={index}>
                {record.timestamp}: 计数变为 {record.value}
              </li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
}

export default AdvancedCounter; 